import { reactive, ref, watch } from 'vue';

import { Modal } from 'ant-design-vue';
import { defineStore } from 'pinia';

import { getShopBindInfo, searchImg } from '#/api';
import { auto1688Store } from '#/store/modules';
// import { getShopBindInfo, loginShop } from '#/api';
const buyLink = import.meta.env.VITE_APP_BUY_DOUDIAN_LINK;
const buy1688Link = import.meta.env.VITE_APP_1688_ISV_URL;

export const indlyfor1688todystor = defineStore('indlyfor1688tody', () => {
  const auto1688 = auto1688Store();
  const selectImage = ref<string>('');
  const images = ref<any>([]);
  const shopData = ref<any>({});
  const imageToGoods = ref<any>([]);
  const imageToGoodsObj = reactive<any>({});
  const selectProducts = ref<any>([]);
  const loading = ref<any>(false);
  const showAddBox = ref<any>(false);
  const selectProductsInOpen = ref<any>([]);

  const infolist = {
    filters: ['jxhy'],
    imageKeywords: '',
  };

  const query = ref<any>({ ...infolist });

  function resetquery() {
    query.value = { ...infolist };
  }
  const buyStatus = reactive<any>({
    buydly: false,
    buy1688: false,
  });
  function prtsecherImage() {
    if (!buyStatus.buy1688 || !buyStatus.buydly) {
      getShopInfo();
      return;
    }
    // console.log('搜索图片');
    getImageForGoods(selectImage.value, true);
  }
  function setSelectImage(image: string) {
    selectImage.value = image;
    if (!buyStatus.buy1688 || !buyStatus.buydly) return;
    getImageForGoods(image);
  }
  function setImages(imgs: any) {
    images.value = imgs;
    if (imgs.length > 0) {
      setSelectImage(imgs[0].url);
    }
  }
  function setShopData(data: any) {
    shopData.value = data;
  }
  function setBuyStatus(data: any) {
    buyStatus.buydly = data.buydly;
    buyStatus.buy1688 = data.buy1688;
  }
  let reloadnum = 0;
  function getImageForGoods(image?: string, isNew?: boolean) {
    if (reloadnum >= 3) {
      imageToGoods.value = [];
      loading.value = false;
      reloadnum = 0;
      return;
    }
    if (!buyStatus.buy1688) return;
    if (
      image &&
      imageToGoodsObj[image] &&
      imageToGoodsObj[image].length > 0 &&
      !isNew
    ) {
      imageToGoods.value = imageToGoodsObj[selectImage.value];
      return;
    }
    loading.value = true;
    // 获取图片
    const queryCopy = { ...query.value };
    queryCopy.filters = queryCopy.filters.join(',');
    searchImg({
      imgUrl: image || selectImage.value,
      ...queryCopy,
    })
      .then((res) => {
        // console.log('ee', res);
        if (res && res.length > 0) {
          imageToGoods.value = res;
          imageToGoodsObj[image || selectImage.value] = res;
          loading.value = false;
          reloadnum = 0;
          return;
        }
        reloadnum++;
        getImageForGoods(image);
        // 获取商品
        // imageToGoods.value = [];
        // loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      })
      .finally(() => {
        loading.value = false;
      });
  }
  function openshowAddBox(values: any) {
    selectProductsInOpen.value = values;
    showAddBox.value = true;
  }

  function toBuyAppMsg() {
    Modal.confirm({
      title: '提示',
      content: '使用当前功能需先授权后使用',
      okText: '去授权',
      cancelText: '取消',
      onOk(clear) {
        window.open(buyLink, '_blank');
        clear && clear();
        userVerify();
        // window.parent.postMessage({ from: 'dly-1688', type: 'bind' }, '*');
      },
    });
  }


  function userVerify() {
    Modal.confirm({
      title: '提示',
      content: '是否成功授权应用',
      okText: '已授权',
      cancelText: '未授权',
      onOk(clear) {
        clear && clear();
        getShopInfo();
      },
    });
  }

  function getShopInfo() {
    getShopBindInfo()
      .then((ress) => {
        loading.value = false;
        auto1688.set1688BindShop(ress);
        const getDlyApp = ress.mapList['2'];
        if (!getDlyApp || getDlyApp.length === 0) {
          toBuyAppMsg();
          return;
        }
        // toBuyAppMsg();
        // toBuy1688App();
        const getusedlyapp = getDlyApp.find(
          (item: any) =>
            item.shopId === shopData.value.shopId && item.status === 1,
        ); //  item.isUseing === 1 &&
        // console.log('getusedlyapp', getusedlyapp);
        if (!getusedlyapp) {
          toBuyAppMsg();
          return;
        }
        // if (getusedlyapp && getusedlyapp.status === 0) {
        //   toBuyAppMsg();
        //   return;
        // }
        setBuyStatus({
          buy1688: false,
          buydly: true,
        });
        //const get1688App = ress.mapList['1'];
        // console.log('get1688App', get1688App);
        // if (!get1688App || get1688App.length === 0) {
        //   toBuy1688App();
        //   return;
        // }
        // console.log('get1688App', get1688App);
        // const getused1688app = get1688App.find(
        //   (item: any) => item.status === 1,
        // ); //  item.isUseing === 1 &&
        // console.log('getused1688app00215646', getused1688app);
        // if (!getused1688app) {
        //   toBuy1688App();
        //   return;
        // }

        // if (getused1688app && getused1688app.status === 0) {
        //   toBuy1688App();
        //   return;
        // }
        setBuyStatus({
          buy1688: true,
          buydly: true,
        });
        getImageForGoods();
      })
      .catch(() => {
        loading.value = false;
      });
  }
  watch(
    selectProducts,
    (newVal) => {
      // console.log('newVal', newVal);
      for (const key in imageToGoodsObj) {
        // console.log('key', imageToGoodsObj[key]);
        let itemsetenum = 0;
        imageToGoodsObj[key].forEach((item: any) => {
          if (newVal.includes(item.offerId)) {
            itemsetenum++;
          }
        });
        images.value.forEach((item: any) => {
          if (item.url === key) {
            item.selectNum = itemsetenum;
          }
        });
        // (imageToGoodsObj[key] as any[]).reduce((pre: any, cur: any) => {
        //   if (newVal.includes(cur.id)) {
        //     pre.push(cur);
        //   }
        //   return pre;
        // });
      }
    },
    {
      deep: true,
    },
  );
  function $reset() {
    selectProducts.value = [];
    images.value = [];
    selectImage.value = '';
    shopData.value = {};
    buyStatus.buydly = false;
    buyStatus.buy1688 = false;
    imageToGoods.value = [];
    loading.value = false;
    selectProductsInOpen.value = [];
    showAddBox.value = false;
  }
  return {
    selectImage,
    setSelectImage,
    images,
    setImages,
    shopData,
    setShopData,
    buyStatus,
    setBuyStatus,
    imageToGoods,
    getImageForGoods,
    loading,
    selectProducts,
    $reset,
    query,
    prtsecherImage,
    resetquery,
    showAddBox,
    openshowAddBox,
    selectProductsInOpen,
    getShopInfo,
    userVerify,
  };
});
